package LinkedListSeries;

public class MyLinkedListSolution_707_2 {
    //size存储链表元素的个数
    int size;
    //虚拟头结点
    ListNode head;

    //初始化链表
    public MyLinkedListSolution_707_2() {
        size = 0;
        head = new ListNode(0);
    }

    public int get(int index) {
        // 下标无效
        if(index < 0 ||index >= size) {
            return -1;
        }

        ListNode cur = head;

        //包含一个虚拟头节点，所以查找第 index+1 个节点
        for (int i = 0; i <= index; i++) {
            cur = cur.next;
        }
        return cur.val;
    }

    public void addAtHead(int val) {
        // 插入到虚拟头结点之后
        ListNode newHeadNode = new ListNode(val);

        newHeadNode.next = head.next;
        head.next = newHeadNode;
        size++;
    }

    public void addAtTail(int val) {
        ListNode newTailNode = new ListNode(val);
        ListNode cur = head;
        while(cur.next != null) {
            cur = cur.next;
        }
        cur.next = newTailNode;
        size++;
    }

    public void addAtIndex(int index, int val) {
        if(index < 0 || index > size) {
            return;
        }

        if (index < 0) {
            index = 0;
        }

        ListNode prev = head;
        ListNode newIndexNode = new ListNode(val);
        for(int i=0; i<index; i++) {
            prev = prev.next; // 找到index前一个结点
        }
        newIndexNode.next = prev.next;
        prev.next = newIndexNode;
        size++;
    }

    public void deleteAtIndex(int index) {
        if(index < 0 || index >= size) {
            return;
        }

        ListNode prev = head;
        for(int i=0; i<index;i++) {
            prev = prev.next; // 找到index前一个结点
        }
        prev.next = prev.next.next;
        size--;
    }
}
